package com.lixinlei.mc.api.sms.cat.util;

import org.smslib.AGateway;
import org.smslib.IOutboundMessageNotification;
import org.smslib.Message.MessageEncodings;
import org.smslib.OutboundMessage;
import org.smslib.Service;
import org.smslib.modem.SerialModemGateway;

import java.util.Date;

public class SendMessageUtil {

    public void doIt(String phone,String content) throws Exception {

        OutboundNotification outboundNotification = new OutboundNotification();
        // ---------------创建串口设备，如果有多个，就创建多个--------------
        // 1、连接网关的 id
        // 2、com口名称，如 COM1 或 /dev/ttyS1（根据实际情况修改）
        // 3、串口波特率，如 9600（根据实际情况修改）
        // 4、开发商
        // 5、型号
        SerialModemGateway gateway = new SerialModemGateway(
                "modem.com3",
                "COM3",
                9600,
                "null",
                "null");
        gateway.setInbound(false);   //设置true，表示该网关可以接收短信,根据需求修改
        gateway.setOutbound(true);  //设置true，表示该网关可以发送短信,根据需求修改
        gateway.setSimPin("0000");  //sim卡锁，一般默认为0000或1234
        //发送短信成功后的回调函方法
        Service.getInstance().setOutboundMessageNotification(outboundNotification);
        Service.getInstance().addGateway(gateway);  //将网关添加到短信猫服务中
        Service.getInstance().startService();   //启动服务，进入短信发送就绪状态
        //打印设备信息
        System.out.println("Modem Information:");
        System.out.println("  Manufacturer: " + gateway.getManufacturer());
        System.out.println("  Model: " + gateway.getModel());
        System.out.println("  Serial No: " + gateway.getSerialNo());
        System.out.println("  SIM IMSI: " + gateway.getImsi());
        System.out.println("  Signal Level: " + gateway.getSignalLevel() + " dBm");
        System.out.println("  Battery Level: " + gateway.getBatteryLevel() + "%");

        //参数1：手机号码 参数2：短信内容
        OutboundMessage msg = new OutboundMessage(phone, content);
        msg.setEncoding(MessageEncodings.ENCUCS2);//这句话是发中文短信必须的
        Service.getInstance().sendMessage(msg); //执行发送短信
        System.out.println(msg);
        System.out.println("Now Sleeping - Hit <enter> to terminate.");
        System.in.read();

        // 关闭服务
        Service.getInstance().stopService();
    }

    public class OutboundNotification implements IOutboundMessageNotification{
        @Override
        public void process(AGateway aGateway, OutboundMessage outboundMessage) {
            System.out.println("Outbound handler called from Gateway: " + aGateway.getGatewayId());
            System.out.println(outboundMessage);
        }
    }

    public static void main(String args[]) {
        SendMessageUtil app = new SendMessageUtil();
        try {
            app.doIt("18599061624", "短信猫测试短信" + new Date());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
